var form = null, path = '', img_jcrop = null, searchObj = parseSearch();

$(function () {
    var fields = "order|url|link", $submit = $('.submit');
    var searchObj = parseSearch();

    /**
     * @date 2017-05-14
     * @desc
     */
    function initPage_() {
        var label = searchObj.edit?'<strong>编辑：</strong>':'';
        if(searchObj.edit){
            $.get("/ads/get?id="+searchObj.id,  function (xhr, data) {
                if (xhr.code == 200) {
                    fields.split('|').map(function (item) {
                        $('[name='+item+']').val(xhr.data[item]);
                    })
                } else {
                    fnFail(xhr.error);
                }
            });
        }
        if (searchObj.type == '1') {
            $('.link-text').show().find('input').val('http://www.hpchem.cn/');
            $('.sug').text('建议尺寸：1200px*80px');
            $('.page-title .title').html(label+'Web详情广告')
        } else if (searchObj.type == '2') {
            $('.link-text').show().find('input').val('http://www.hpchem.cn/');
            $('.sug').text('建议尺寸：500px*150px');
            $('.page-title .title').html(label+'微信详情广告')
        }

    }
    initPage_();
    $('.cancel').click(function () {
        window.location = './index.html?type=' + (searchObj.type || 0);
    });
    $(".form-horizontal").validate({
        submitHandler: function (form_) {
            var form = {};
            $submit.button('loading');
            fields.split('|').map(function (item) {
                form[item] = form_[item].value;
            });
            form.type = searchObj.type || 0;
            form.status = 2;
            var　url  ="/ads/create";
            if(searchObj.edit){
                url = "/ads/update";
                form.id = searchObj.id;
            }
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    alert('保存成功!');
                    window.location = './index.html?type=' + (searchObj.type || 0);
                } else {
                    alert(xhr.error);
                }
                $submit.button('reset');
            });
            return false;
        }
    });

    $('.upload-tips').click(function () {
        $(this).siblings('input').click();
    });
    $("#file1").change(function () {
        upload(this);
    });
    function upload(self) {
        ajaxFileUpload({
            eleId: $(self).attr('id')
        }, function (data) {
            if (!data) {
                $('input[type=file]').unbind('change').on('change', function () {
                    upload(this);
                });
                return;
            }
            $("#upload").attr("src", data.data.path);
            $("[name=url]").val(data.data.path);
        });
    }

});